package dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import domain.ContactGroup;

public class DAOGroup extends HibernateDaoSupport {

	public List<String> search() {
		@SuppressWarnings("unchecked")
		List<String> groups = (List<String>) this.getHibernateTemplate().find(
				"select distinct g.groupName from ContactGroup g");
		return groups;
	}

	public ContactGroup find(String name) {
		if (name == null)
			return null;
		HibernateTemplate templ = this.getHibernateTemplate();
		@SuppressWarnings("unchecked")
		List<ContactGroup> groups = (List<ContactGroup>) templ
				.findByNamedParam(
						"from ContactGroup c where c.groupName = :name",
						"name", name);
		if (groups != null && groups.size() > 0)
			return groups.get(0);
		return null;
	}

	public void createRefrence(int idContact, int idGroup) {
		Session session = this.getSessionFactory().openSession();
		Transaction trans = session.beginTransaction();
		session.createSQLQuery(
				"insert into t_contact_group(ID_CONTACT,GROUPID) values ("
						+ idContact + "," + idGroup + ")").executeUpdate();
		trans.commit();
		session.close();
	}
}
